<template>
	<!-- 文件平铺 -->
	<div class="file-grid-wrapper">
    <n-spin :show="props.loading">
		<ul
			class="file-list"
		>
			<li
				class="file-item"
				v-for="(item, index) in fileList"
				:key="index"
				:title="fileFunction.getFileNameComplete(item)"
				:style="`width: ${gridSize + 40}px; `"
				:class="item.userFileId === selectedFile.userFileId ? 'active' : ''"
				@click="fileFunction.handleFileNameClick(item, index, fileList)"
                @contextmenu="handleContextMenu(item, index, $event)"
			>
				<video
					:style="`height:${gridSize}px; width:${gridSize}px`"
					v-if="fileFunction.isVideoFile(item)"
					:src="fileFunction.setFileImg(item)"
				></video>
				<n-image
					class="file-img"
					:src="fileFunction.setFileImg(item)"
					:style="`width: ${gridSize}px; height: ${gridSize}px;`"
                    preview-disabled
					v-else
				/>
				<div
					class="file-name"
					v-html="fileFunction.getFileNameComplete(item, true)"
				></div>

				<div
					class="file-checked-wrapper"
					:class="{ checked: item.checked }"
					v-show="isBatchOperation"
					@click.stop.self="item.checked = !item.checked"
				>
					<n-checkbox
						class="file-checked"
            :checked="item.checked"
						@click.stop="item.checked = !item.checked"
					></n-checkbox>
				</div>
			</li>
		</ul>
    </n-spin>
	</div>
    <n-dropdown
        placement="bottom-start"
        trigger="manual"
        :x="xRef"
        :y="yRef"
        :options="options"
        :show="showDropdownRef"
        :on-select="handleSelect"
        :on-clickoutside="clickoutside"
    />
</template>

<script lang="ts" setup>
import {Component, computed, h, nextTick, onMounted, ref, watch} from "vue";
import {FilePanStore} from "@/store/modules/file";
import fileFunction from '@/libs/globalFunction/file.js'
import {DropdownOption, NIcon} from "naive-ui";
import {
    Eye as EyeIcon,
    TrashBin as TrashBinIcon,
    Copy as CopyIcon,
    Navigate as NavigateIcon,
    Pencil as PencilIcon,
    Share as ShareIcon,
    Download as DownloadIcon,
    FileTrayFull as FileTrayFullIcon,
} from '@vicons/ionicons5'
//@ts-ignore
import Bus from "@/components/file/box/GlobalUploader/utils/bus";
import {storeToRefs} from "pinia";
import {useUserStore} from "@/store/modules/useUserStore";
import {store} from "@/store";
import {storage} from "@/hooks/useStorage";
const {authorization, tokenKey} = storeToRefs(useUserStore(store));
const token = authorization?.value ?? storage.get(tokenKey?.value as string);

const filePanStore = FilePanStore();

/**
 * 当前选中文件
 */
const selectedFile = ref({})

const showDropdownRef = ref(false)
const xRef = ref(0)
const yRef = ref(0)

/**
 * 图标渲染
 * @param icon
 */
const renderIcon = (icon: Component) => {
    return () => h(NIcon, null, { default: () => h(icon) })
}

const options = [
    {
        label: '查看',
        key: 'preview',
        icon: renderIcon(EyeIcon)
    },
    {
        label: '删除',
        key: 'delete',
        icon: renderIcon(TrashBinIcon)
    },
    {
        type: 'divider',
        key: 'd1'
    },
    {
        label: '复制',
        key: 'copy',
        icon: renderIcon(CopyIcon)
    },{
        label: '移动',
        key: 'move',
        icon: renderIcon(NavigateIcon)
    }, {
        label: '重命名',
        key: 'rename',
        icon: renderIcon(PencilIcon)
    },
    {
        type: 'divider',
        key: 'd1'
    },
    // ,{
    //     label: '分享',
    //     key: 'share',
    //     icon: renderIcon(ShareIcon)
    // },
  {
        label: '下载',
        key: 'download',
        icon: renderIcon(DownloadIcon)
    }
    // , {
    //     label: '文件详情',
    //     key: 'fileDetail',
    //     icon: renderIcon(FileTrayFullIcon)
    // }
]


const props = defineProps({
    fileType : {
        required: true,
        type: Number
    },
    filePath : {
        required: true,
        type: String
    },
    fileList: Array,
    loading: Boolean
})


const officeFileType =  ['ppt', 'pptx', 'doc', 'docx', 'xls', 'xlsx']

const gridSize = computed(() => {
    return filePanStore.getGridSize;
})

const isBatchOperation = computed(() => {
    return filePanStore.getIsBatchOperation;
})




const selectedFileList = computed(() => {
  if(props.fileList){
    let res = props.fileList.filter((item:any) => item.checked)
    return res
  }

})

watch([selectedFileList],() => {
  if(selectedFileList) {
    filePanStore.changeSelectedFiles(selectedFileList.value)
  }
})



const handleContextMenu = (item:any,index:any,e:MouseEvent) =>{
    // 组织右键事件冒泡
    e.preventDefault()
    showDropdownRef.value = false
    selectedFile.value = item
    nextTick().then(() => {
        showDropdownRef.value = true
        xRef.value = e.clientX
        yRef.value = e.clientY
    })
}
const clickoutside = () =>{
    showDropdownRef.value = false
}


watch([props.fileList],(newValue,oldValue) => {
    console.log("fileList, selectedFileListchanged")
  console.log(newValue,oldValue)
})

const handleSelect=(key:string|number) => {
    if(key === 'preview') {
        fileFunction.handleFileNameClick(selectedFile.value,0,[selectedFile.value])
    }
    if(key ==='download') {
        let link = document.createElement("a")
        link.style.display = 'none'
        link.href = fileFunction.getDownloadFilePath(selectedFile.value) +"&token="+token
        link.setAttribute('download', '导出img')
        document.body.appendChild(link)
        link.click()
    }
    if(key === 'delete') {
      // Bus.emit('imgPreview', {imgList, currentIndex})
      let isBatchOperation = false
      let fileInfo= selectedFile.value
      console.log(props.fileType)
      console.log(fileInfo)
      let deleteMode = props.fileType===6?2:1
      // 单独操作
      Bus.emit('showDeleteFile',{isBatchOperation , fileInfo, deleteMode})
    }

    if(key === 'copy'){
      let fileInfo = selectedFile.value
      Bus.emit('showCopyFileDialog',{fileInfo})
    }

    if(key === 'move'){
      let isBatchOperation = false
      let fileInfo= selectedFile.value
      console.log(props.fileType)
      let deleteMode = props.fileType===6?2:1
      Bus.emit('showMoveFileDialog',{isBatchOperation , fileInfo, deleteMode})
    }


    if(key == 'rename'){
      let oldName = selectedFile.value.fileName
      let userFileId = selectedFile.value.userFileId
      Bus.emit('showRenameFileDialog',{oldName,userFileId})
    }
    showDropdownRef.value = false

}

</script>

<style lang="stylus" scoped>

.file-grid-wrapper {
  border-top: 1px solid $BorderBase;

  .file-list {
    height: calc(100vh - 275px);
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
    align-content: flex-start;
    list-style: none;
    setScrollbar(6px, transparent, #C0C4CC);

    .file-item {
      margin: 0 16px 16px 0;
      position: relative;
      padding: 8px;
      text-align: center;
      cursor: pointer;
      z-index: 1;

      &:hover {
        //background: #F5F7FA;
        .file-name {
          font-weight: 650;
        }
      }

      .file-name {
        margin-top: 8px;
        height: 44px;
        line-height: 22px;
        font-size: 12px;
        word-break: break-all;
        display: -webkit-box;
        overflow: hidden;
        white-space: wrap;
        text-overflow: ellipsis;
        -webkit-box-orient: vertical; /* -webkit-box-orient 必须结合的属性 ，设置或检索伸缩盒对象的子元素的排列方式 */
        -webkit-line-clamp: 2; /* -webkit-line-clamp用来限制在一个块元素显示的文本的行数 */
        >>> .keyword {
          color: $Danger;
        }
      }

      .file-checked-wrapper {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2;
        background: rgba(245, 247, 250, 0.5);
        width: 100%;
        height: 100%;

        .file-checked {
          position: absolute;
          top: 16px;
          left: 24px;
        }
      }

      .file-checked-wrapper.checked {
        background: rgba(245, 247, 250, 0);
      }
    }
    .file-item.active {
      background: $tabBackColor;
    }
  }

  .right-menu-list {
    position: fixed;
    display: flex;
    flex-direction: column;
    background: #fff;
    border: 1px solid $BorderLighter;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 2;
    padding: 4px 0;
    color: $RegularText;

    .right-menu-item,
    .unzip-item {
      padding: 0 16px;
      height: 36px;
      line-height: 36px;
      cursor: pointer;
      &:hover {
        background: $PrimaryHover;
        color: $Primary;
      }
      i {
        margin-right: 8px;
      }
    }

    .unzip-menu-item {
      position: relative;
      &:hover {
        .unzip-list {
          display: block;
        }
      }
      .unzip-list {
        position: absolute;
        display: none;
        .unzip-item {
          width: 200px;
          setEllipsis(1)
        }
      }
    }
  }
  .right-menu-list,
  .unzip-list {
    background: #fff;
    border: 1px solid $BorderLighter;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 2;
    padding: 4px 0;
    color: $RegularText;
  }
}
</style>
